package com.heba.greenmulu.user;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.heba.ATApp;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.bean.ItemAreaObject;
import com.heba.dialog.YearMonthSelectDialog;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.MemberShipHelper;
import com.heba.helper.TakePhotoHelper;
import com.heba.permission.PermissionHelper;
import com.heba.popupwindow.AddressPopupWindow;
import com.heba.popupwindow.PhotoPopupWindow;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ImageTools;
import com.heba.utils.ToastShow;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.CosXmlSimpleService;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.listener.CosXmlResultListener;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;
import com.tencent.cos.xml.transfer.TransferConfig;
import com.tencent.cos.xml.transfer.TransferManager;
import com.tencent.cos.xml.transfer.TransferState;
import com.tencent.cos.xml.transfer.TransferStateListener;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 用户修改个人信息页面
 * <p>
 * Created by jason on 2019/2/12.
 */

public class UserModifyActivity extends BaseActivity {

    private View view_background;
    private ImageView img_avatar;
    private EditText edit_first_name;
    private EditText edit_last_name;
    private Button btn_female;
    private Button btn_male;
    private TextView txt_month;
    private TextView txt_year;
    private TextView txt_address;
    private Button btn_confirm;

    /**
     * 头像上传
     */
    private PhotoPopupWindow photoPopupWindow;
    private File tempFile;   //头像保存路径
    private int crop = 500;  //裁剪大小
    private String imgUrl = "";   //上传图片地址

    /**
     * 地址弹出框
     */
    private AddressPopupWindow addressPopupWindow;
    private List<ItemAreaObject> itemAreaObjects = new ArrayList<>();

    /**
     * 腾讯云文件存储对象
     */
    private CosXmlServiceConfig serviceConfig;
    private CosXmlSimpleService cosXmlSimpleService;
    private String appid = "1253933048";
    private String region = "ap-guangzhou";

    /**
     * 设置默认年月日
     */
    private int sex = 0;
    private int year = 1980;
    private int month = 6;
    private int day = 1;
    private String address = "";
    private String addressEN = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_modify);
        initTopbar();
        findViewById();
        initView();
        initData();
        initCosClient();
        initPopWindow();
    }

    /**
     * 初始化cosClient
     */
    private void initCosClient() {
        //初始化 cosClient
        serviceConfig = new CosXmlServiceConfig.Builder().setAppidAndRegion(appid, region).setDebuggable(true).builder();
        /**
         * 初始化对象，来给SDK提供临时密钥。
         */
        QCloudCredentialProvider credentialProvider = new ShortTimeCredentialProvider(ATApp.CosSecretId,
                ATApp.CosSecretKey, 300);
        cosXmlSimpleService = new CosXmlSimpleService(this, serviceConfig, credentialProvider);
    }

    /**
     * 初始化PopupWindow
     */
    private void initPopWindow() {
        /**
         * 照片弹出框
         */
        photoPopupWindow = new PhotoPopupWindow(this, ViewGroup.LayoutParams.MATCH_PARENT, DensityUtils.dip2px(this, 165));

        photoPopupWindow.setOnPhotoPopupClickListener(new PhotoPopupWindow.OnPhotoPopupClickListener() {
            @Override
            public void onCameraClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.takePicture(UserModifyActivity.this, tempFile);
            }

            @Override
            public void onAlbumClick() {
                tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
                TakePhotoHelper.selectPhoto(UserModifyActivity.this);
            }

            @Override
            public void onCancelClick() {

            }
        });

        photoPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });

        /**
         * 地址弹出框
         */
        addressPopupWindow = new AddressPopupWindow(this, DensityUtils.getWidth(this),
                2 * DensityUtils.getHeight(this) / 5);
        addressPopupWindow.adapter = new AddressPopupWindow.ItemListAdapter(this, itemAreaObjects);
        addressPopupWindow.listView.setAdapter(addressPopupWindow.adapter);

        addressPopupWindow.setOnCategoryPopupClickListener(new AddressPopupWindow.OnAddressPopupClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemAreaObject object = (ItemAreaObject) parent.getItemAtPosition(position);
                address = object.getLocationZH();
                addressEN = object.getLocationEN();
                if (Cfg.Leng == 0) {
                    txt_address.setText(addressEN);
                } else {
                    txt_address.setText(address);
                }
            }
        });

        addressPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void findViewById() {
        view_background = findViewById(R.id.view_background);
        img_avatar = findViewById(R.id.img_avatar);
        edit_first_name = findViewById(R.id.edit_first_name);
        edit_last_name = findViewById(R.id.edit_last_name);
        btn_female = findViewById(R.id.btn_female);
        btn_male = findViewById(R.id.btn_male);
        btn_confirm = findViewById(R.id.btn_confirm);
        txt_month = findViewById(R.id.txt_month);
        txt_year = findViewById(R.id.txt_year);
        txt_address = findViewById(R.id.txt_address);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.modify_data));

        img_avatar.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            view_background.setVisibility(View.VISIBLE);
            getCameraPermission();
        });

        btn_female.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            btn_male.setSelected(false);
            btn_female.setSelected(true);
            sex = 2;
        });

        btn_male.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            btn_male.setSelected(true);
            btn_female.setSelected(false);
            sex = 1;
        });

        txt_month.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            getMonthDialog();
        });

        txt_year.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            getYearDialog();
        });

        /**
         * 地址选择
         */
        txt_address.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            addressPopupWindow.showAtLocation(img_avatar, Gravity.BOTTOM, 0, 0);
            view_background.setVisibility(View.VISIBLE);
        });

        /**
         * 确认事件监听
         */
        btn_confirm.setOnClickListener(v -> {
            DensityUtils.hideSoftWindow(this, edit_first_name);
            updateInfo();
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        imgUrl = Cfg.Icon;
        GlideUtil.loadImageWithPlaceHolderID(this, Cfg.Icon, img_avatar, R.drawable.icon_head_portrait);
        edit_first_name.setText(Cfg.NickName);
        edit_last_name.setText(Cfg.LastName);
        if (Cfg.Sex.equals("1")) {
            sex = 1;
            btn_male.setSelected(true);
        } else if (Cfg.Sex.equals("2")) {
            sex = 2;
            btn_female.setSelected(true);
        }
        year = Integer.valueOf(Cfg.BirthYear);
        month = Integer.valueOf(Cfg.BirthMonth);
        txt_year.setText(Cfg.BirthYear);
        //显示月份，中英文版本显示不同
        String[] months = getResources().getStringArray(R.array.array_month);
        if (month > 0) {
            if (months[month - 1].length() >= 3) {
                txt_month.setText(months[month - 1].substring(0, 3));
            } else {
                txt_month.setText(months[month - 1]);
            }
        }

        address = Cfg.Address;
        addressEN = Cfg.Addressen;
        if (Cfg.Leng == 0) {
            txt_address.setText(addressEN);
        } else {
            txt_address.setText(address);
        }

        /**
         * 地区数据
         */
        String[] location_zh = this.getResources().getStringArray(R.array.select_location_zh);
        String[] location_en = this.getResources().getStringArray(R.array.select_location_en);
        for (int i = 0; i < location_zh.length; i++) {
            ItemAreaObject itemAreaObject = new ItemAreaObject();
            itemAreaObject.setLocationZH(location_zh[i]);
            itemAreaObject.setLocationEN(location_en[i]);
            itemAreaObjects.add(itemAreaObject);
        }
    }

    /**
     * 更新信息
     */
    private void updateInfo() {
        /**
         * check empty
         */
        if (edit_first_name.getText().toString().trim().isEmpty() || edit_last_name.getText().toString().trim().isEmpty() || sex == 0
                || txt_year.getText().toString().isEmpty() || txt_month.getText().toString().isEmpty() || txt_address.getText().toString().trim().isEmpty()) {
            ToastShow.displayToast(this, getResources().getString(R.string.sign_up_message_tips));
            return;
        }

        progressDialog.show();
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                progressDialog.dismiss();
                finishActivity();
                ToastShow.displayToast(UserModifyActivity.this, getResources().getString(R.string.update_success));
            }

            @Override
            public void Fail(String error) {
                progressDialog.dismiss();
            }
        }).setUserInfo(UserModifyActivity.this, imgUrl, edit_first_name.getText().toString(), edit_last_name.getText().toString(), sex, month, year, address, addressEN);
    }

    /**
     * 获取摄像头,读取文件权限
     */
    private void getCameraPermission() {
        new PermissionHelper(UserModifyActivity.this, new PermissionHelper.PermissionListener() {
            @Override
            public void onPermissionSuccess() {
                photoPopupWindow.showAtLocation(img_avatar, Gravity.BOTTOM, 0, 0);
            }

            @Override
            public void onPermissionFailure() {

            }
        }).requestPermission(Permission.WRITE_EXTERNAL_STORAGE, Permission.CAMERA);
    }

    /**
     * 获取年份(年龄必须大于18岁)
     */
    private void getYearDialog() {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        //只获取年龄大于18岁
        List<String> list = new ArrayList();
        for (int i = currentYear - 18; i > 1900; i--) {
            list.add(i + "");
        }
        /**
         * 显示年份对话框
         */
        new YearMonthSelectDialog(new YearMonthSelectDialog.OnDialogClickListener() {
            @Override
            public void onItemClick(String content) {
                year = Integer.valueOf(content);
                txt_year.setText(content);
            }

            @Override
            public void onItemMonthClick(String content, int position) {

            }
        }).getYearsDialog(this, list);

    }

    /**
     * 获取月份
     */
    private void getMonthDialog() {
        new YearMonthSelectDialog(new YearMonthSelectDialog.OnDialogClickListener() {
            @Override
            public void onItemClick(String content) {

            }

            @Override
            public void onItemMonthClick(String content, int position) {
                month = position + 1;
                if (content.length() >= 3) {
                    txt_month.setText(content.substring(0, 3));
                } else {
                    txt_month.setText(content);
                }
            }
        }).getMonthDialoh(this, this.getResources().getStringArray(R.array.array_month));
    }

    /**
     * 显示日期对话框
     */
    private void showDatePickDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
                //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
                year = myyear;
                month = monthOfYear;
                day = dayOfMonth;

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, monthOfYear);
                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                txt_year.setText(year + "");
                txt_month.setText(String.format("%02d", (month + 1)));

            }
        }, year, month, day);
        datePickerDialog.show();
    }

    /**
     * --------------------------- 相册或拍照获取图片部分 ----------------------------------
     */

    /**
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TakePhotoHelper.TAKE_PICTURE:
                    // 拍照裁剪图片
                    TakePhotoHelper.cropImage(UserModifyActivity.this, tempFile, Uri.fromFile(tempFile), crop,
                            TakePhotoHelper.PICTURE_SEND);
                    break;

                case TakePhotoHelper.CHOOSE_PICTURE:
                    // 相册选取图片去裁剪
                    if (data != null) {
                        TakePhotoHelper.cropImage(UserModifyActivity.this, tempFile, data.getData(), crop,
                                TakePhotoHelper.PICTURE_SEND);
                    }
                    break;

                case TakePhotoHelper.PICTURE_SEND:
                    if (tempFile != null)
                        sentPicToNext(tempFile);
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 将进行剪裁后的图片传递到下一个界面上
     *
     * @param file
     */
    private void sentPicToNext(File file) {
        //解决小米系统 retuen data 为null的问题
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.fromFile(file)));
            //图片路径
            String localPath = ImageTools.savePhotoToSDCard(this, bitmap, ImageTools.getUploadPathFolder(), ImageTools.getFileName(), false);
            String cosPath = "greenmulu/image/transfer_" + ImageTools.getFileName();
            if (bitmap != null) {
                loading.Start();
                img_avatar.setImageBitmap(bitmap);
                upload(localPath, cosPath);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param srcPath
     * @param cosPath
     */
    private void upload(String srcPath, String cosPath) {
        // 初始化 TransferConfig
        TransferConfig transferConfig = new TransferConfig.Builder().build();
        TransferManager transferManager = new TransferManager(cosXmlSimpleService, transferConfig);

        String bucket = "greenmulu";
        String uploadId = null;//用于续传，若无，则为null.
        //上传文件
        COSXMLUploadTask cosxmlUploadTask = transferManager.upload(bucket, cosPath, srcPath, uploadId);
        //设置上传进度回调
        cosxmlUploadTask.setCosXmlProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long complete, long target) {
                float progress = 1.0f * complete / target * 100;
                Debug.Log("upload", String.format("progress = %d%%", (int) progress));
            }
        });
        //设置返回结果回调
        cosxmlUploadTask.setCosXmlResultListener(new CosXmlResultListener() {
            @Override
            public void onSuccess(CosXmlRequest request, CosXmlResult result) {
                loading.End();
                if (!result.accessUrl.startsWith("http://") && !result.accessUrl.startsWith("https://")) {
                    imgUrl = "http://" + result.accessUrl;
                } else {
                    imgUrl = result.accessUrl;
                }
                Debug.Log("upload success", "imgUrl = " + imgUrl);
            }

            @Override
            public void onFail(CosXmlRequest request, CosXmlClientException exception, CosXmlServiceException serviceException) {
                loading.End();
                Debug.Log("upload", "Failed: " + (exception == null ? serviceException.getMessage() : exception.toString()));
            }
        });
        //设置任务状态回调, 可以查看任务过程
        cosxmlUploadTask.setTransferStateListener(new TransferStateListener() {
            @Override
            public void onStateChanged(TransferState state) {
                Debug.Log("upload", "Task state:" + state.name());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Debug.Log("清理上传图片的文件夹", ImageTools.getUploadPathFolder().toString());
        //清理文件图片
        ImageTools.deleteAllPhoto(ImageTools.getUploadPathFolder());
    }
}
